import smtplib
import unittest, time, os
from HTMLTestRunner import HTMLTestRunner
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


# 发送邮件
def send_mail(file):
    f = open(file, 'rb')
    mail_body = f.read()
    f.close()
    msg = MIMEText(mail_body, 'html', 'utf-8')
    msg['Subject'] = Header('测试报告', 'utf-8')
    # ——————上面的写法是用html页面作为内容发送的方式 下面注释掉的是作为附件发送——————
    # f = open(file, 'rb').read()
    # att = MIMEText(f, 'base64', 'utf-8')
    # att["Content-Type"] = 'application/octet-stream'
    # att["Content-Disposition"] = 'attachment;filename=' + file + ''
    # msg = MIMEMultipart('related')
    # msg['Subject'] = '测试报告'
    # msg['from'] = 'lichunmei55@126.com'
    # msg['to'] = '787360118@qq.com'
    # msg.attach(att)
    # ————————
    smtp = smtplib.SMTP()
    smtp.connect('smtp.126.com')
    smtp.login('lichunmei55@126.com', '')
    smtp.sendmail('lichunmei55@126.com', '787360118@qq.com', msg.as_string())
    smtp.quit()
    print('email has send out')


# 查找最新文件
def new_file(file_path):
    lists = os.listdir(file_path)
    lists.sort(key=lambda fn: os.path.getmtime(file_path + '\\' + fn))
    file = os.path.join(file_path, lists[-1])
    print(file)
    return file


if __name__ == '__main__':
    now = time.strftime('%Y-%m-%d %H_%M_%S')
    file_path = './test_report'
    test_dir = './test_case'
    discover = unittest.defaultTestLoader.discover(test_dir, pattern='test_*.py')

    fp = open(file_path + '\\' + now + 'result.html', 'wb')
    runner = HTMLTestRunner(stream=fp, title='测试报告', description='用例执行情况')
    runner.run(discover)
    fp.close()

    new_report = new_file(file_path)
    send_mail(new_report)
